package com.mm.cloud.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mm.cloud.common.core.enums.DeleteEnum;
import com.mm.cloud.common.core.exception.BaseException;
import com.mm.cloud.common.core.result.Result;
import com.mm.cloud.common.core.result.ResultConstants;
import com.mm.cloud.common.core.result.ResultUtil;
import com.mm.cloud.common.security.annotation.ParameterCheck;
import com.mm.cloud.common.security.helper.LoginUserHelper;
import com.mm.cloud.common.security.loginuser.LoginUser;
import com.mm.cloud.sys.dto.form.DictItemDTO;
import com.mm.cloud.sys.entity.DictItem;
import com.mm.cloud.sys.mapper.DictItemMapper;
import com.mm.cloud.sys.service.IDictItemService;
import com.mm.cloud.sys.vo.DictItemVO;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典数据 服务实现类
 * </p>
 *
 * @author mr
 * @since 2022-11-12
 */
@Service
public class DictItemServiceImpl extends ServiceImpl<DictItemMapper, DictItem> implements IDictItemService {

    @Override
    @ParameterCheck
    public Result<List<DictItemVO>> getDictItemList(@NotNull(message = "字典类型ID不能为空") Long dictTypeId) {
        List<DictItem> list = this.list(Wrappers.<DictItem>lambdaQuery()
                .eq(DictItem::getDictTypeId, dictTypeId)
                .eq(DictItem::getIsDelete, DeleteEnum.NOT_DELETE.getStatus())
                .orderByAsc(DictItem::getSort));
        return ResultUtil.success(list.stream().map(v -> {
            DictItemVO vo = new DictItemVO();
            BeanUtils.copyProperties(v, vo);
            return vo;
        }).collect(Collectors.toList()));
    }

    @Override
    @ParameterCheck
    public Result<String> saveDictItem(DictItemDTO dto) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        // 校验字典标签
        DictItem exitstDictItem = this.getOne(Wrappers.<DictItem>lambdaQuery()
                .eq(DictItem::getDictTypeId, dto.getDictTypeId())
                .eq(DictItem::getDictItemLabel, dto.getDictItemLabel())
                .eq(DictItem::getIsDelete, DeleteEnum.NOT_DELETE.getStatus()));
        if (Objects.nonNull(exitstDictItem)) {
            return ResultUtil.fail("字典标签已使用");
        }
        // 校验字典标签
        exitstDictItem = this.getOne(Wrappers.<DictItem>lambdaQuery()
                .eq(DictItem::getDictTypeId, dto.getDictTypeId())
                .eq(DictItem::getDictItemValue, dto.getDictItemValue())
                .eq(DictItem::getIsDelete, DeleteEnum.NOT_DELETE.getStatus()));
        if (Objects.nonNull(exitstDictItem)) {
            return ResultUtil.fail("字典值已使用");
        }
        DictItem dictItem = new DictItem();
        BeanUtils.copyProperties(dto, dictItem);
        dictItem.setCreaterId(loginUser.getUserId());
        dictItem.setCreateTime(LocalDateTime.now());
        dictItem.setIsDelete(DeleteEnum.NOT_DELETE.getStatus());
        this.save(dictItem);
        return ResultUtil.success();
    }

    @Override
    @ParameterCheck
    public Result<String> updateDictItem(DictItemDTO dto) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        DictItem dictItem = this.getDictItemAssert(dto.getId());
        // 校验字典标签
        DictItem exitstDictItem = this.getOne(Wrappers.<DictItem>lambdaQuery()
                .eq(DictItem::getDictTypeId, dto.getDictTypeId())
                .eq(DictItem::getDictItemLabel, dto.getDictItemLabel())
                .eq(DictItem::getIsDelete, DeleteEnum.NOT_DELETE.getStatus())
                .ne(DictItem::getId, dto.getId()));
        if (Objects.nonNull(exitstDictItem)) {
            return ResultUtil.fail("字典标签已使用");
        }
        // 校验字典标签
        exitstDictItem = this.getOne(Wrappers.<DictItem>lambdaQuery()
                .eq(DictItem::getDictTypeId, dto.getDictTypeId())
                .eq(DictItem::getDictItemValue, dto.getDictItemValue())
                .eq(DictItem::getIsDelete, DeleteEnum.NOT_DELETE.getStatus())
                .ne(DictItem::getId, dto.getId()));
        if (Objects.nonNull(exitstDictItem)) {
            return ResultUtil.fail("字典值已使用");
        }
        BeanUtils.copyProperties(dto, dictItem);
        dictItem.setUpdaterId(loginUser.getUserId());
        dictItem.setUpdateTime(LocalDateTime.now());
        this.updateById(dictItem);
        return ResultUtil.success();
    }

    @Override
    @ParameterCheck
    public Result<String> deleteDictItem(@NotNull(message = "参数不能为空") Long dictItemId) {
        LoginUser loginUser = LoginUserHelper.getLoginUser();
        DictItem dictItem = this.getDictItemAssert(dictItemId);
        dictItem.setUpdaterId(loginUser.getUserId());
        dictItem.setUpdateTime(LocalDateTime.now());
        dictItem.setIsDelete(DeleteEnum.DELETE.getStatus());
        this.updateById(dictItem);
        return ResultUtil.success();
    }

    /**
     * 查询字典数据
     *
     * @param dictItemId 字典数据ID
     * @return DictItem
     */
    private DictItem getDictItemAssert(Long dictItemId) {
        Assert.notNull(dictItemId, "dictItemId is null");
        DictItem dictItem = this.getOne(Wrappers.<DictItem>lambdaQuery().eq(DictItem::getId, dictItemId).eq(DictItem::getIsDelete, DeleteEnum.NOT_DELETE.getStatus()));
        if (Objects.isNull(dictItem)) {
            throw new BaseException(ResultConstants.QUERY_NOT_FOUND_DATA);
        }
        return dictItem;
    }
}
